package com.cenntro.auth.controllers;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cenntro.auth.common.RoleTypeEnum;
import com.cenntro.auth.model.dbo.SysPermissionDO;
import com.cenntro.auth.model.dbo.SysRoleDO;
import com.cenntro.auth.model.dbo.SysSooidDO;
import com.cenntro.auth.model.dbo.SysSooidRoleRefDO;
import com.cenntro.auth.model.vo.SysRoleDetailVO;
import com.cenntro.auth.model.vo.SysRoleVO;
import com.cenntro.auth.service.SysPermissionService;
import com.cenntro.auth.service.SysRoleService;
import com.cenntro.auth.service.SysSooidRoleRefService;
import com.cenntro.auth.utils.AgentPathUtil;
import com.cenntro.auth.utils.Valid;
import com.cenntro.common.base.BaseController;
import com.cenntro.common.model.vo.PageVO;
import com.cenntro.common.model.vo.TreeUtil;
import com.cenntro.common.model.vo.TreeVO;
import com.cenntro.common.util.ConvertorUtils;
import com.cenntro.common.util.MessageUtil;
import com.cenntro.common.util.result.PageResult;
import com.cenntro.common.util.result.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Api(value = "角色role", tags = { "角色" })
@RestController
@RequestMapping("/role")
@Slf4j
public class RoleController extends BaseController {

    @Resource
    private SysRoleService roleService;

    @Resource
    private SysPermissionService sysPermissionService;

    @Resource
    private SysSooidRoleRefService sysSooidRoleRefService;

    /**
     * 
    * @Title 创建角色
    * @Description 1、管理员创建agent 角色 agentId 字段 0，
    *              2、其他 agentId 字段未客户端传入
    * @param 
    * @return
     */
    @RequestMapping(value = "/add")
    @ApiOperation(value = "角色新增", notes = "新增角色")
    public Result add(@Validated(value = { Valid.insert.class }) SysRoleVO sysRoleVO) {
        log.info(sysRoleVO.toString());
//            String agentPath = AgentPathUtil.getAgentPathByRole(null);
//        Subject subject = SecurityUtils.getSubject();
//        int roleType = (Integer) subject.getSession().getAttribute("roleType");
//        if (roleType == 1 && (sysRoleVO.getRoleType().equals(1) || sysRoleVO.getRoleType().equals(2))) {
//            sysRoleVO.setAgentId(0);
//        }
        int count = roleService.insert(sysRoleVO);
        if (count > 0) {
            return Result.ok();
        }
        return Result.error(MessageUtil.PARAM_ILLEGAL, MessageUtil.getMsg("ROLE_NAME_EXISTS", sysRoleVO.getRoleName()));
    }

    @RequestMapping(value = "/getRoleType")
    @ApiOperation(value = "角色分类", notes = "角色分类")
    public Result getRoleType() {
        int roleType = AgentPathUtil.getRoleType();
        List<Map<String, Object>> roleTypes = com.google.common.collect.Lists.newArrayList();
        if (roleType == 1) {
            for (RoleTypeEnum rte : RoleTypeEnum.values()) {
                roleTypes.add(ImmutableMap.of("type", rte.getName(), "value", rte.getType()));
            }
        } else {
            roleTypes.add(ImmutableMap.of("type", RoleTypeEnum.GENERAL.getName(), "value", RoleTypeEnum.GENERAL.getType()));
        }
        return Result.ok(roleTypes);
    }

    /**
     * 
     * @param sysRoleVO
     * @return
     */
    @ApiOperation(value = "查询角色详情", notes = "查询角色详情")
    @RequestMapping(value = "/selectById")
    @ApiModelProperty(value = "角色id，不能是空")
    public Result selectById(Integer roleId) {
        SysRoleDO role = roleService.selectById(roleId);
        SysRoleDetailVO detailVO = ConvertorUtils.deepConvert(role, SysRoleDetailVO.class);
        String roleTypeName = RoleTypeEnum.getByType(detailVO.getRoleType()).getName();
        detailVO.setRoleTypeName(roleTypeName);
        List<SysPermissionDO> perms = sysPermissionService.selectPermByRoleIds(Lists.newArrayList(role.getRoleId()));
        List<?> tree = new TreeUtil<SysPermissionDO>() {

            @Override
            public boolean isRootId(SysPermissionDO e, TreeVO pNode) {
                if (e.getPNode().replace(e.getPermissionId().toString(), "").equals("0_")) {
                    return true;
                }
                return false;
            }

            @Override
            public boolean isParentId(SysPermissionDO e, TreeVO pNode) {
                String[] ids = e.getPNode().split("_");
                int index = ArrayUtils.indexOf(ids, pNode.getId().toString());
                return index == (ids.length - 2);
            }

            @Override
            public String getRootId(SysPermissionDO e, TreeVO pNode) {
                if (e.getPNode().replace(e.getPermissionId().toString(), "").equals("0_")) {
                    return e.getPermissionId().toString();
                } else {
                    return pNode.getRootId();
                }
            }

            @Override
            public void setField(SysPermissionDO e, TreeVO treeVO) {
                treeVO.setId(e.getPermissionId());
                treeVO.setName(e.getName());
                treeVO.setUrl(e.getUrl());
            }
        }.toTree(null, perms);
        detailVO.setPermTree(tree);
        return Result.ok(detailVO);
    }

    /**
     * 
    * @Title 创建角色
    * @Description 1、管理员创建agent 角色 agentId 字段 0，
    *              2、其他 agentId 字段未客户端传入
    * @param 
    * @return
     */
    @RequestMapping(value = "/update")
    @ApiOperation(value = "修改角色", notes = "根据id修改角色")
    @ApiImplicitParam(name = "roleId", required = true, paramType = "query", value = "修改id不能是空")
    public Result update(@Validated(value = { Valid.update.class }) SysRoleVO sysRoleVO) {
        log.info(sysRoleVO.toString());
//        String agentPath = AgentPathUtil.getAgentPath(null);
//        Subject subject = SecurityUtils.getSubject();
//        int roleType = (Integer) subject.getSession().getAttribute("roleType");
//        if (roleType == 1 && (sysRoleVO.getRoleType().equals(1) || sysRoleVO.getRoleType().equals(2))) {
//            sysRoleVO.setAgentId(0);
//        }
        int count = roleService.update(sysRoleVO);
        if (count > 0) {
            return Result.ok();
        } else {
            return Result.error(MessageUtil.PARAM_ILLEGAL,
                    MessageUtil.getMsg("ROLE_NAME_EXISTS", sysRoleVO.getRoleName()));
        }
    }

    /**
     * 查询角色列表
     * 
     * @param sysRoleVO
     * @return
     */
    @ApiOperation(value = "查询角色列表", notes = "查询角色列表")
    @RequestMapping(value = "/selectPage")
    @ApiModelProperty(value = "角色名称，不能是空")
    public Result selectPage(SysRoleVO sysRole, PageVO pageVO) {
        Page<SysRoleDO> page = PageHelper.startPage(pageVO.getPage(), pageVO.getLimit(), true);
        SysRoleDO sysRoleDO = ConvertorUtils.deepConvert(sysRole, SysRoleDO.class);
//        Subject subject = SecurityUtils.getSubject();
//        SysSooidDO user = (SysSooidDO) subject.getPrincipal();
//        int roleType = (Integer) subject.getSession().getAttribute("roleType");
//        if (roleType == 2) {
//            sysRoleDO.setAgentId(user.getAgentId());
//        }
        List<SysRoleDO> roleList = roleService.selectPage(sysRoleDO);
        return PageResult.ok(roleList, page.getTotal());
    }

    /**
     * 
     * @param sysAuthVO
     * @return
     */
    @CrossOrigin
    @ApiOperation(value = "删除角色", notes = "删除角色")
    @RequestMapping(value = "/delete")
    @ApiModelProperty(value = "删除角色")
    public Result delete(Integer roleId) {
        SysSooidRoleRefDO sysSooidRoleRef = new SysSooidRoleRefDO();
        sysSooidRoleRef.setRoleId(roleId);
        int count = sysSooidRoleRefService.selectCount(sysSooidRoleRef);
        if (count > 0) {
            return Result.error("有用户关联该角色，请先删除用户");
        }
        SysRoleVO sysRoleVO = new SysRoleVO();
        sysRoleVO.setRoleId(roleId);
        sysRoleVO.setStatus(-1);
        roleService.update(sysRoleVO);
        return Result.ok();
    }
}
